package com.linq.cool.auth.service;

import com.linq.cool.api.domain.SysLoginLog;
import com.linq.cool.api.dto.SysUserLastLoginDTO;
import com.linq.cool.api.feign.RemoteBeautyMemberService;
import com.linq.cool.api.feign.RemoteSysLogService;
import com.linq.cool.api.feign.RemoteSysUserService;
import com.linq.cool.api.vo.LoginUser;
import com.linq.cool.api.vo.SysUserVO;
import com.linq.cool.api.vo.WebLoginUser;
import com.linq.cool.common.constants.CacheConstants;
import com.linq.cool.common.constants.Constants;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.domain.Result;
import com.linq.cool.common.core.exception.BaseException;
import com.linq.cool.common.core.exception.user.*;
import com.linq.cool.common.core.utils.*;
import com.linq.cool.common.redis.service.RedisService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: yqlin
 * @Date: 2021/1/3 02:01
 * @Description: 登录校验方法
 * @Version: 1.0.0
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteSysLogService remoteSysLogService;
    @Autowired
    private RemoteBeautyMemberService remoteBeautyMemberService;
    @Autowired
    private RemoteSysUserService remoteSysUserService;
    @Autowired
    private RedisService redisService;

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录成功用户信息
     */
    public LoginUser doLogin(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "用户/密码必须填写"));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH ||
                password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "用户密码不在指定范围"));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH ||
                username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "用户名不在指定范围"));
            throw new UserUsernameNotMatchException();
        }
        // 查询用户信息
        Result<LoginUser> userResult = remoteSysUserService.getUserInfo(username);
        if (Result.FAIL.equals(userResult.getCode())) {
            throw new BaseException(userResult.getMessage());
        }
        if (StringUtils.isNull(userResult.getData())) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "登录用户不存在"));
            throw new UserNotExistsException();
        }
        LoginUser userInfo = userResult.getData();
        SysUserVO userVO = userResult.getData().getSysUserVO();
        if (UserConstants.StateEnum.DELETE_FLAG_DELETED.getCode().equals(userVO.getIsDeleted())) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除"));
            throw new UserDeleteException();
        }
        if (UserConstants.StateEnum.STATUS_DISABLE.getCode().equals(userVO.getStatus())) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员"));
            throw new UserBlockedException();
        }
        if (!SecurityUtils.matchesPassword(password, userVO.getPassword())) {
            remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_FAIL, "用户密码错误"));
            throw new UserPasswordInvalidException();
        }
        remoteSysLogService.saveLoginLog(this.composeSysLoginLog(username, Constants.LOGIN_SUCCESS, "登录成功"));
        SysUserLastLoginDTO dto = new SysUserLastLoginDTO();
        dto.setId(userInfo.getSysUserVO().getId())
                .setLastLoginIp(IpUtils.getIpAddr(Objects.requireNonNull(ServletUtils.getRequest())))
                .setLastLoginTime(new Date());
        Result<?> ret = remoteSysUserService.updateLoginInfo(dto);
        if (Result.FAIL.equals(ret.getCode())) {
            throw new BaseException(ret.getMessage());
        }
        return userInfo;
    }

    /**
     * 构造访问记录日志
     *
     * @param username
     */
    private SysLoginLog composeSysLoginLog(String username, String status, String message) {
        SysLoginLog loginLog = new SysLoginLog();
        final UserAgent userAgent = UserAgent.parseUserAgentString(Objects.requireNonNull(ServletUtils.getRequest()).getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        String city = AddressUtils.getRealAddressByIp(ip);
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            loginLog.setStatus(0);
        }
        if (Constants.LOGIN_FAIL.equals(status)) {
            loginLog.setStatus(1);
        }
        loginLog.setUsername(username)
                .setMessage(message)
                .setOs(os).setBrowser(browser).setCity(city).setIp(ip)
        ;
        return loginLog;
    }

    /**
     * 登录
     *
     * @param phone    手机号
     * @param password 密码
     * @return 登录成功用户信息
     */
    public WebLoginUser doWebLogin(String phone, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(phone, password)) {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH ||
                password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (phone.length() < UserConstants.USERNAME_MIN_LENGTH ||
                phone.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new UserUsernameNotMatchException();
        }
        // 查询用户信息
        Result<WebLoginUser> userResult = remoteBeautyMemberService.getFrontMemberInfo(phone);
        if (Result.FAIL.equals(userResult.getCode())) {
            throw new BaseException(userResult.getMessage());
        }
        if (StringUtils.isNull(userResult.getData())) {
            throw new UserNotExistsException();
        }
        WebLoginUser userInfo = userResult.getData();
        if (UserConstants.StateEnum.STATUS_DISABLE.getCode().equals(userInfo.getStatus())) {
            throw new UserBlockedException();
        }
        if (!SecurityUtils.matchesPassword(password, userInfo.getPassword())) {
            throw new UserPasswordInvalidException();
        }
        // 判断当前用户是否已经登录 如果登录了 我们就把另外一个登陆的人给踢掉
        this.kickWebLoginUser(userInfo);
        return userInfo;
    }

    private void kickWebLoginUser(WebLoginUser currentUser) {
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            String token = key.replace(CacheConstants.LOGIN_TOKEN_KEY, "");
            Integer loginType = JwtUtils.getLoginType(token);
            if (UserConstants.StateEnum.LOGIN_TYPE_WEB.getCode().equals(loginType)) {
                WebLoginUser webLoginUser = redisService.getCacheObject(key);
                //   可以重写 WebLoginUser euqals方法
                if (currentUser.equals(webLoginUser)) {
                    redisService.deleteObject(key);
                }
            }
        }
    }

    public void logout(String loginName) {
        remoteSysLogService.saveLoginLog(this.composeSysLoginLog(loginName, Constants.LOGOUT, "退出成功"));
    }
}
